package com.zxb.base.soc.service.impl;

import com.zxb.base.soc.service.ReplyService;
import com.zxb.core.common.R;
import com.zxb.core.common.Req;
import com.zxb.core.common.User;
import com.zxb.core.dao.auth.AuthUser;
import com.zxb.core.dao.auth.AuthUserDao;
import com.zxb.core.dao.soc.SocReply;
import com.zxb.core.dao.soc.SocReplyDao;
import com.zxb.core.dao.soc.SocTopic;
import com.zxb.core.dao.soc.SocTopicDao;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author Zxb
 */
@Service
@AllArgsConstructor
public class ReplyServiceImpl implements ReplyService {

    private AuthUserDao userDao;
    private SocTopicDao topicDao;
    private SocReplyDao replyDao;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public R<?> addFirst(Long topicId, String content) {
        User u = Req.getCurrUser();
        AuthUser user = userDao.getById(u.getId());
        SocTopic topic = topicDao.getById(topicId);
        SocReply reply = new SocReply();
        reply.setLayer(1);
        reply.setPraiseTimes(0);
        reply.setReplyTimes(0);
        reply.setTopicId(topicId);
        reply.setUserId(user.getId());
        reply.setUserName(user.getName());
        reply.setUserHead(user.getHead());
        reply.setContent(content);
        replyDao.save(reply);
        Integer replyTimes = topic.getReplyTimes();
        topic.setReplyTimes(replyTimes == null ? 1 : replyTimes + 1);
        topicDao.updateById(topic);
        return R.success(reply);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public R<?> addNext(Long replyId, String content) {
        User u = Req.getCurrUser();
        AuthUser user = userDao.getById(u.getId());
        SocReply parent = replyDao.getById(replyId);
        SocTopic topic = topicDao.getById(parent.getTopicId());
        SocReply reply = new SocReply();
        reply.setLayer(parent.getLayer() + 1);
        reply.setPraiseTimes(0);
        reply.setReplyTimes(0);
        reply.setTopicId(parent.getTopicId());
        reply.setUserId(user.getId());
        reply.setUserName(user.getName());
        reply.setUserHead(user.getHead());
        reply.setContent(content);
        reply.setPid(replyId);
        replyDao.save(reply);
        parent.setReplyTimes(parent.getReplyTimes() + 1);
        replyDao.updateById(parent);
        topic.setReplyTimes(topic.getReplyTimes() + 1);
        topicDao.updateById(topic);
        return R.success(reply);
    }

}
